import { QualityControlEntity } from "@scmt/api-lis-quality-control";
import { EditFormProps, useNotify } from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { useApi } from "@scmt/core-api";

interface IProps {
  onSaved?: () => void;
}

const _editingObj = ref<null | QualityControlEntity>(null);

export const useEditPackage = (props?: IProps) => {
  const $api = useApi();
  const $notify = useNotify();

  const { onSaved } = Object.assign({}, props);

  const { loading, request } = useRequest({
    save: async (model: QualityControlEntity) => {
      return $api.lis.qualityControl.save(model).then(() => {
        $notify.success("保存成功");
        _editingObj.value = null;

        if (typeof onSaved === "function") {
          onSaved();
        }
      });
    },
  });

  const formItems: EditFormProps["items"] = [
    {
      prop: "packageName",
      label: "质控包名称",
      required: true,
    },
    {
      prop: "packageCode",
      label: "质控包编码",
      required: false,
    },
    {
      prop: "packageManufacturer",
      label: "质控包厂商",
      required: false,
    },
    {
      prop: "concentration",
      label: "浓度",
      required: true,
      as: "checkbox-group",
      options: {
        loadMethod: () => {
          return [
            {
              label: "高浓度",
              value: 1,
            },
            {
              label: "中浓度",
              value: 2,
            },
            {
              label: "低浓度",
              value: 3,
            },
          ];
        },
      },
    },
    {
      prop: "concentrationLevel",
      label: "浓度水平",
      required: false,
      as: "input-number",
    },
    {
      prop: "batchNumber",
      label: "质控物批号",
      required: false,
    },
    {
      prop: "materialName",
      label: "质控物名称",
      required: false,
    },
    {
      prop: "periodEffect",
      label: "质控物期效",
      required: false,
      as: "date",
    },
    {
      prop: "sampleNumber",
      label: "质控标本号",
      required: false,
    },
  ];

  const editFormProps = computed<EditFormProps>(() => {
    const editProps: EditFormProps = {
      model: _editingObj.value,
      items: formItems,
      columns: 2,
      size: "middle",
      loading: loading.value,
      onClose: () => {
        _editingObj.value = null;
      },
      onCancel: () => {
        _editingObj.value = null;
      },
      onValidate: (model) => {
        request("save", model);
      },
    };

    return editProps;
  });

  const editPackage = (model?: QualityControlEntity) => {
    _editingObj.value = $api.lis.qualityControl.$$createEntity(model);
  };

  return {
    editFormProps,
    editPackage,
  };
};
